package cn.com.infcn.monitor.task.jvm.impl;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;

import javax.management.MBeanServerConnection;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.infcn.monitor.bean.IFCResponseBean;
import cn.com.infcn.monitor.jvm.bean.IFCJVMOperatingSystem;
import cn.com.infcn.monitor.task.impl.BaseTask;
import cn.com.infcn.monitor.util.IFCBeanUtils;
import cn.com.infcn.monitor.util.IFCMinitorConstanst;

/**
 * 用于操作系统的管理接口，Java 虚拟机在此操作系统上运行。
 * 
 * @author jijs
 *
 */
public class JVMOperatingSystemTask extends BaseTask {

	private final static Logger logger = LoggerFactory.getLogger(JVMOperatingSystemTask.class);

	public JVMOperatingSystemTask(IoSession session, Object message) {
		super(session, message);
	}

	@Override
	public void execute() throws Exception {
		IFCResponseBean result = jvmOperatingSystem();
		sendResponse(result);
	}

	public IFCResponseBean jvmOperatingSystem() {
		IFCResponseBean result = new IFCResponseBean();
		IFCJVMOperatingSystem ifcOperatingSystem = null;

		MBeanServerConnection mbs = null;
		try {
			// 获取MBeanServerConnection
			mbs = MBeanServerConnectionFactory.getInstance(IFCMinitorConstanst.JMXURL);
		} catch (IOException e) {
			logger.error("jmx.url 连接异常！" + e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg("jmx.url 连接异常！");
			return result;
		}

		try {

			OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.newPlatformMXBeanProxy(mbs,
					ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);
			ifcOperatingSystem = new IFCJVMOperatingSystem();

			IFCBeanUtils.copyProperties(operatingSystemMXBean, ifcOperatingSystem);

			result.setResult(ifcOperatingSystem);
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_OK);

		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setResponseCode(IFCMinitorConstanst.MONITOR_RESPONSE_CODE_ERROR);
			result.setResponseMsg(e.getMessage());
		}

		return result;
	}

	public static void main(String[] args) {
		JVMOperatingSystemTask task = new JVMOperatingSystemTask(null, null);
		IFCResponseBean result = task.jvmOperatingSystem();
		IFCJVMOperatingSystem ifcOperatingSystem = (IFCJVMOperatingSystem) result.getResult();

		System.out.println(ifcOperatingSystem.getAvailableProcessors());
		System.out.println(ifcOperatingSystem.getSystemLoadAverage());
		System.out.println(ifcOperatingSystem.getName());
		System.out.println(ifcOperatingSystem.getArch());
		System.out.println(ifcOperatingSystem.getVersion());

	}

}
